<?php

namespace App\Http\Controllers;

use App\Models\Combination;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Response;
use App\Models\Fund;
use Illuminate\Support\Facades\Cache;

class BookmarkController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('bookmark.index');
    }

    public function fund()
    {
        return view('bookmark.fund');
    }

    public function getList(){
    	$result = Fund::orderBy('next_day', 'ASC')->get();
    	return response()->json($result);
    }

    public function script()
    {
        set_time_limit(0);
        $list = Fund::where('week_rank', 0)->get();
        foreach ($list as $key => $value) {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, 'http://fund.eastmoney.com/' . $value['code'] . '.html');
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            $rs = curl_exec($ch);
            curl_close($ch);
            preg_match_all('/基金类型：.*?\<\/a\>/', $rs, $type);
            $input['type'] = preg_replace('/基金类型：/', '', strip_tags($type[0][0]));
            preg_match_all('/\<div class="fundDetail\-tit"\>\<div style="float\: left"\>.*?\<span\>/', $rs, $name);
            $input['name'] = strip_tags($name[0][0]);
            preg_match_all('/\<div class="jjpj\d{0,1}/', $rs, $rate);
            $input['rate'] = str_replace('<div class="jjpj', '', $rate[0][0]);
            if (empty($rate)) $rate = 0;
            preg_match_all('/\<div class="Rdata">\d{0,5}/', $rs, $rank);
            $input['week_rank'] = str_replace('<div class="Rdata">', '', $rank[0][0]);
            $input['month_rank'] = str_replace('<div class="Rdata">', '', $rank[0][1]);
            Fund::where('code', $value['code'])->update($input);
            echo $value['code'] . ' done<br />';
            sleep(3);
        }
    }

    private function _curl($url){
        $headers = [
            'Accept' => '*/*',
            'Accept-Encoding' => 'gzip, deflate, sdch, br',
            'Host' => 'xueqiu.com',
//            'Upgrade-Insecure-Requests' => '1',
            'User-Agent' =>  'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36',
            'X-Requested-With' => 'XMLHttpRequest',
        ];

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        // curl_setopt($ch, CURLOPT_HEADER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_COOKIE, 'aliyungf_tc=AQAAAMwEUn98xgoAbOJ4DpIMH4zMDJ5S; s=ej1qalifx1; device_id=5a0420729a908e92152341c91da9bfb4; __utma=1.1199430332.1508721412.1508721412.1508721412.1; __utmb=1.3.9.1508721412; __utmc=1; __utmz=1.1508721412.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); Hm_lvt_1db88642e346389874251b5a1eded6e3=1507598595; Hm_lpvt_1db88642e346389874251b5a1eded6e3=1508721811; xq_a_token=98a690239fc32de38936e61fbcc0e6237db26a42; xqat=98a690239fc32de38936e61fbcc0e6237db26a42; xq_r_token=0fd53b0def682a076b7c70463129ac449810d33c; xq_is_login=1; u=8111372191; xq_token_expire=Fri%20Nov%2017%202017%2009%3A41%3A42%20GMT%2B0800%20(CST)');
        $rs = curl_exec($ch);
        curl_close($ch);

        if($rs === false) {
            throw new \Exception('Curl error: ' . curl_error($ch) . $url);
        }
        return json_decode($rs);
    }

    public function jk()
    {
        return view('bookmark.jk');
    }

    public function sync()
    {
        set_time_limit(0);
        $combs = ['ZH600792', 'ZH973683'];
        $notice = [];

        foreach ($combs as $c) {
            /*Cache::forget($c);*/
            $url = "https://xueqiu.com/cubes/rebalancing/history.json?cube_symbol={$c}&count=3&page=1";
            $rs  = $this->_curl($url);
            $log = Cache::get($c);
//            dump($log);
            if (empty($log)) {
                $log = [];
            }

            foreach ($rs->list as $k => $v) {
                if (in_array($v->status, ['canceled', 'failed'])) { // 'pending'
                    continue;
                }

                if (in_array($v->id, $log)) {
                    continue;
                } else {
                    array_unshift($log, $v->id);
                    array_push($notice, "https://xueqiu.com/cubes/rebalancing/history.json?cube_symbol={$c}&count=2&page=1");
                    Cache::forever($c, $log);
                }
            }
        }

        return response()->json($notice);
    }

    public function update_comb()
    {
        set_time_limit(0);
        $comb     = Combination::where('earnings1d', 0)->orderBy('id', 'asc')->first();
        if (empty($comb)) {
            dd('done!');
        }

        $now      = time() . '000';
        $time1d   = strtotime('today') . '000';
        $time1w   = strtotime('-7 days') . '000';
        $time1m   = strtotime('-30 days') . '000';
        $time3m   = strtotime('-90 days') . '000';
        $time6m   = strtotime('-180 days') . '000';
        $time1y   = strtotime('-360 days') . '000';

        $url = "https://xueqiu.com/cubes/nav_daily/all.json?cube_symbol={$comb->code}&since={$time1d}&until={$now}";
        $rs = $this->_curl($url);
        $comb->name = $rs[0]->name;
        $data_len = count($rs[0]->list);
        $comb->earnings1d = $rs[0]->list[$data_len - 1]->percent;

        $url = "https://xueqiu.com/cubes/nav_daily/all.json?cube_symbol={$comb->code}&since={$time1w}&until={$now}";
        $rs = $this->_curl($url);
        $comb->name = $rs[0]->name;
        $data_len = count($rs[0]->list);
        $comb->earnings1w = $rs[0]->list[$data_len - 1]->percent;

        $url = "https://xueqiu.com/cubes/nav_daily/all.json?cube_symbol={$comb->code}&since={$time1m}&until={$now}";
        $rs = $this->_curl($url);
        $comb->name = $rs[0]->name;
        $data_len = count($rs[0]->list);
        $comb->earnings1m = $rs[0]->list[$data_len - 1]->percent;

        $url = "https://xueqiu.com/cubes/nav_daily/all.json?cube_symbol={$comb->code}&since={$time3m}&until={$now}";
        $rs = $this->_curl($url);
        $comb->name = $rs[0]->name;
        $data_len = count($rs[0]->list);
        $comb->earnings3m = $rs[0]->list[$data_len - 1]->percent;

        $url = "https://xueqiu.com/cubes/nav_daily/all.json?cube_symbol={$comb->code}&since={$time6m}&until={$now}";
        $rs = $this->_curl($url);
        $comb->name = $rs[0]->name;
        $data_len = count($rs[0]->list);
        $comb->earnings6m = $rs[0]->list[$data_len - 1]->percent;

        $url = "https://xueqiu.com/cubes/nav_daily/all.json?cube_symbol={$comb->code}&since={$time1y}&until={$now}";
        $rs = $this->_curl($url);
        $comb->name = $rs[0]->name;
        $data_len = count($rs[0]->list);
        $comb->earnings1y = $rs[0]->list[$data_len - 1]->percent;

        $url = "https://xueqiu.com/cubes/analyst/histo/stat.json?type=volatility&cube_symbol={$comb->code}";  //收益波动
        $rs = $this->_curl($url);
        $comb->volatility_name = $rs->volatility_name;
        $comb->volatility_rate = round($rs->volatility_rate, 2);

//        $url = "https://xueqiu.com/cubes/analyst/histo/stat.json?type=max_draw&cube_symbol={$comb->code}";   //最大回撤
//        $rs = $this->_curl($url);
//        $comb->max_draw = $rs->max_draw;
//
//        $url = "https://xueqiu.com/cubes/analyst/histo/stat.json?cube_symbol={$comb->code}&type=turnover";   //换手率
//        $rs = $this->_curl($url);
//        $comb->turnover3m = $rs->values[0]->value;
//        $comb->turnover12m = $rs->values[2]->value;
//
//        $url = "https://xueqiu.com/cubes/analyst/histo/stat.json?cube_symbol={$comb->code}&type=liquidity";  //流动性
//        $rs = $this->_curl($url);
//        $comb->liquidity3m = $rs->values[0]->value;
//        $comb->liquidity12m = $rs->values[2]->value;
        $comb->save();

        sleep(5);

        return redirect('update_comb');
    }

    public function cul_max_draw()
    {
        $data = [1, 1.02, 1.01];
        $max = 0;
        $temp = 0;
        foreach ($data as $k=>$v) {
            $temp = max($temp, $v);
            $max  = min($max, $v/$temp - 1);
        }
        dump(round($max, 2));
    }
}
